# coding=utf-8
from Database_Config import *
import tornado.ioloop
import tornado.web
import datetime
import json
import sys
import logging
from logging.handlers import RotatingFileHandler

reload(sys)
sys.setdefaultencoding('utf-8')

def dictfetchall(cursor):
  columns = [col[0] for col in cursor.description]
  rows = [dict(zip(columns, row)) for row in cursor.fetchall()]
  return rows

i = 0

FILENAME = "logs/" + sys.argv[1] + ".log";
FORMAT = "%(asctime)-15s %(message)s"
logging.basicConfig(format = FORMAT, filename = FILENAME, level = logging.DEBUG)
logging.getLogger('tornado.access').disabled = True
RotatingFileHandler(FILENAME, mode='a', maxBytes=1*1024*1024,
                     backupCount=1, encoding=None, delay=0)

class SetTag(tornado.web.RequestHandler):
    def set_default_headers(self):
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Headers", "x-requested-with")
        self.set_header('Access-Control-Allow-Methods',
                        'POST, PUT, GET, OPTIONS')

    def post(self):
        sql = self.request.body
        if "UACS_WEB_TAG_QUEUE" not in sql:
            self.set_status(400)
            return self.write("tag queue only")
        try:
            c = conn_ibm_dbi.cursor()
            c.execute(sql)
            conn_ibm_dbi.commit()
            return self.write("OK")
        except Exception, ex:
            self.set_status(400)
            return self.write(str(ex))


class GetData(tornado.web.RequestHandler):
    def set_default_headers(self):
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Headers", "x-requested-with")
        self.set_header('Access-Control-Allow-Methods',
                        'POST, PUT, GET, OPTIONS')

    def post(self):
        sql = self.request.body
        if sql[0:6].lower() != "select" and sql[0:6].lower() != "update" and sql[0:6].lower() != "insert":
            self.set_status(400)
            return self.write("select, insert and update only")
        try:
            c = conn_ibm_dbi.cursor()
            if sql[0:6].lower() == "select":
                c.execute(sql)
		rows = dictfetchall(c)
                global i
                if i == 100:
                    logging.info(self.request.headers["CLIENT_IP"])
                    i = 0
                else:
                    i += 1
                # print(datetime.datetime.now(), self.request.headers["CLIENT_IP"])
                return self.write(json.dumps(rows, indent=4, sort_keys=True, default=str, ensure_ascii=False).encode("utf8"))
            elif sql[0:6].lower() == "insert" and "UACS_WEB_USER_ACTIVITY" in sql:
                sql = sql.replace("$IP", self.request.headers["CLIENT_IP"])
                c.execute(sql)
                conn_ibm_dbi.commit()
                return self.write("OK")
            else:
                c.execute(sql)
                conn_ibm_dbi.commit()
                return self.write("OK")
        except Exception, ex:
            self.set_status(400)
            logging.error(ex)
            return self.write(str(ex))


def make_app():
    return tornado.web.Application([
        (r"/api/setter", SetTag),
        (r"/api/query", GetData),
    ], debug=False)


if __name__ == "__main__":
    try:
        app = make_app()
        app.listen(sys.argv[1])
        tornado.ioloop.IOLoop.current().start()
    except Exception, ex:
        logging.error(ex) 
